import TxOss from 'cos-js-sdk-v5'
import { getAuth } from '@/api/cos/cos'

const txClient = new TxOss({
  getAuthorization: (options, callback) => {
    // 异步获取临时密钥
    getAuth(options.Bucket, options.Region).then(res => {
      if (!res.data.credential) {
        return console.error('credentials invalid')
      }
      const credential = res.data.credential
      callback({
        TmpSecretId: credential.credentials.tmpSecretId,
        TmpSecretKey: credential.credentials.tmpSecretKey,
        XCosSecurityToken: credential.credentials.sessionToken,
        // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
        StartTime: credential.startTime, // 时间戳，单位秒，如：1580000000
        ExpiredTime: credential.expiredTime // 时间戳，单位秒，如：1580000900
      })
    })
  }
})

export default txClient
